<template>
    <div class="Table">
        <div class="left_Nav">
            <div class="row">
                <div class="form-row-label">
                    {{ $t("message.bhView.leftComponents.device") }}
                </div>
                <el-select v-model="valuePlant" class="form-ipt" @change="getPlantApi(1, 1000)">
                    <el-option v-for=" item in plantOptions " :key="item.pltCode" :label="item.pltName"
                        :value="item.pltCode"></el-option>
                </el-select>
            </div>
            <div class="Tbale" style="position: relative;" :class="changeEditMode == 0 ? 'mask' : ''">
                <ux-grid ref="multipleTable" :data="TableData" style="width: 100%" :header-cell-style="{
                    color: 'rgb(0, 0, 0)',
                    fontSize: '14px',
                    textAlign: 'center',
                    fontWeight: '500',
                    padding: 0,
                    height: '32px',
                    background: 'rgba(233, 233, 233, 1)',

                }" :cell-style="{
                    color: 'rgba(96,98,102,1)',
                    fontSize: '14px',
                    padding: 0,
                    height: '23px',
                    margin: '0'
                }" :row-style="{
                    color: 'rgba(96,98,102,1)',
                    fontSize: '13px',
                    textAlign: 'left',
                    padding: 0,
                    height: '23px',
                }" @current-change="handleCurrentChange" :height="tableHeight"
                    :element-loading-text="$t('message.bhView.loading')">
                    <template slot="empty"> No data </template>
                    <ux-table-column property="partsCode" width="47" type="index" align="center">
                    </ux-table-column>

                    <ux-table-column property="proName" align="center" title="処理系">
                        <template slot-scope="scope">
                            <div style="text-align: center;">
                                {{ scope.row.proName }}
                            </div>
                        </template>
                    </ux-table-column>

                    <ux-table-column width="50" property="dummy" align="center" title=" ">
                        <template slot-scope="scope">
                            <el-image style="
								width: 17px;
								height: 17px;
								padding: 2px;
								margin-top: 4px;
							" :src="scope.row.dummy ? checkImg : uncheckImg" fit="fill"></el-image>
                        </template>
                    </ux-table-column>

                </ux-grid>
            </div>

            <div class="bh-footer">
                <div class="bh-footer-msg">
                    {{ $t("message.bhView.WallThicknessPattern.number") }}
                    {{ TableData.length }}
                    {{ $t("message.bhView.WallThicknessPattern.piece") }}
                </div>

            </div>

            <div class="bottonBtn" style="position: relative;" :class="changeEditMode == 0 ? 'mask' : ''">
                <!-- <el-button size="mini" :disabled="!(changeEditMode == 1 && activeRow.dummy)" @click="delAreaDataFn">
                    解除
                </el-button>
                <el-button type="primary" size="mini" :disabled="!(changeEditMode == 1 && activeMackUp)"
                    @click="areaRelaPfdFn">
                    関連付け
                </el-button> -->
                <el-button size="mini" @click="delAreaDataFn"
                    :disabled="TableData.length == 0 || TableData.filter(item => item.dummy != 0).length == 0">
                    解除
                </el-button>
                <el-button type="primary" size="mini" @click="areaRelaPfdFn">
                    関連付け
                </el-button>
            </div>

        </div>
        <div class="right_Content">
            <div class="row">
                <div class="selectViewLabel">
                    プロットプラン
                </div>
                <el-select class="form-ipt" v-model="MapValue" @change="MapValueChange">
                    <el-option v-for=" item in MapList" :key="item.areaCode" :label="item.areaName"
                        :value="item.areaCode"></el-option>
                </el-select>
                <span>{{ activeMackUp.prlNo }}</span>
                <span class="iconfont" :class="changeEditMode == 0 ? '' : 'isActive'"
                    @click="changeEditModeFn">&#xec7c;</span>
                <!-- <div class="refresh" @click="getFullFieldMarkApi(MapValue)">
                    <i class="iconfont">&#xe81f;</i>
                </div> -->
                <!-- <el-button size="mini" @click="TestFn">TEST-{{ changeEditMode }}</el-button> -->
            </div>
            <div id="right-CAD" class="right-CAD" ref="rightCAD" :class="changeEditMode == 0 ? 'mask' : ''"></div>
        </div>
    </div>
</template>

<script>
import $ from "jquery";
import { getPlant, getFullFieldMapList, getPfdByPlant, getFullFieldMark, areaRelaPfd, GetSavePlantRegTipsMsg, delAreaData } from "@/api/api";
import { getLocalStorage } from "@/utils/storage";
import EventBus from "@/eventBus/bus";
import _ from 'lodash-es';
import { showLoading, hideLoading } from "@/utils/loading";
import * as svg_opt from "@/utils/svg_opt.js";
export default {
    name: "DeviceLoginIndex",
    data() {
        return {
            TableData: [],
            tableHeight: '550',

            checkImg: require("@/assets/img/checkbox_sel.png"),
            uncheckImg: require("@/assets/img/checkbox_unsel.png"),

            plantOptions: [],
            valuePlant: Number(this.$store.state.pltCode),
            MapList: [],
            MapValue: 8,
            pfdData: [],
            changeEditMode: 0,// 0:关闭   1：开启
            sourceUrl: '',

            activeMackUp: {
                prlNo: ''
            },
            activeRow: {
                dummy: 0
            },
            activeIndex: 0,
            originExt: ""

        };
    },
    components: {
    },
    props: [],// 1列表2列表-图形
    watch: {

    },
    methods: {
        TestFn() {
            this.getPfdByPlantApi();
        },
        // 左侧列表逻辑
        async getPlantApi(pageIndex = 1, pageSize = 1000) {
            svg_opt.changeSelectStatusById(0);
            this.changeEditMode = 0;
            let dataJson = {
                pltCode: 0,
                platName: "",
                pageIndex,
                pageSize,
            };
            let res = await getPlant(dataJson)
            this.plantOptions = [];
            if (res.data.code != 0) {
                return;
            }
            this.plantOptions = res.data.data;
            if (this.valuePlant == 0) {
                this.$store.commit("changePltCode", 9);
            }
            // this.valuePlant = this.valuePlant == 0 ? 9 : this.valuePlant;

            this.$store.commit("changePltCode", this.valuePlant);
			this.plantOptions.forEach((Item) => {
				if (Item.pltCode == this.valuePlant) {
					this.$store.commit(
						"changeThreeRelationPlantName",
						Item.pltName
					);
				}
			});
            
            // 确认装之后，获取列表
            this.getPfdByPlantApi();
        },
        // 切换装置--逻辑待完善
        PlantChange() {
            // 更新保存的装置code
            this.$store.commit("changePltCode", this.valuePlant);
            // 更新保存的装置name
            this.plantOptions.forEach((Item) => {
                if (Item.pltCode == this.valuePlant) {
                    let valuePlant = Item.pltName;
                    this.$store.commit("changePlantName", valuePlant);
                    this.$store.commit("changePrnCode", Item.prnCode);
                }
            });

        },
        // 获取列表
        async getPfdByPlantApi(AreaNo) {
            let dataJson = {
                PltCode: this.valuePlant,
                AreaCode: this.MapValue,
                AreaNo,
            };
            let res = await getPfdByPlant(dataJson)
            this.TableData = [];
            if (res.data.code != 0) {
                return;
            }
            this.TableData = res.data.data;
            this.TableData.forEach((item, index) => {
                item.id = index;
            })
            this.activeRow = {};
            // this.$refs.multipleTable.setCurrentRow(this.TableData[this.activeIndex]);
            // this.activeRow = this.TableData[this.activeIndex];
            // 延迟防止markup未加载成功
            // setTimeout(() => {
            //     svg_opt.changeSelectStatusById(this.activeRow.areaNo, false);
            // }, 200);
        },
        // 列表选择--逻辑待完善
        handleCurrentChange(e) {
            console.log(e);
            this.activeRow = e;
            this.activeIndex = e.id;

            // svg_opt.changeSelectStatusById(e.areaNo, false);
            return
        },
        // 右侧图形逻辑
        // 获取右侧下拉框
        async getFullFieldMapListApi() {
            let dataJson = {};
            let res = await getFullFieldMapList(dataJson)
            this.MapList = [];
            if (res.data.code != 0) {
                return;
            }
            this.MapList = res.data.data;
            this.MapValue = this.MapList[0].areaCode;

            let num = this.MapList[0].originFileName.lastIndexOf(".") + 1;
            this.originExt = this.MapList[0].originFileName.substring(num);

            // svg图处理
            this.svgStartFn(this.MapList[0].areaFile);
            this.getFullFieldMarkApi(this.MapList[0].areaCode);
            // 获取列表
            this.getPlantApi();
        },
        async MapValueChange(value) {
            this.changeEditMode = 0;
            let areaFile = this.MapList.filter(item => item.areaCode == value)[0].areaFile || '';

            let num = this.MapList[value - 1].originFileName.lastIndexOf(".") + 1;
            this.originExt = this.MapList[value - 1].originFileName.substring(num);

            console.log('areaFile', areaFile);
            // areaFile = 'http://192.168.33.89:8085\\aaa\\pfd\\web\\PFD.svg';
            this.svgStartFn(areaFile, value);
            // this.getFullFieldMarkApi(value);

            this.getPfdByPlantApi();

            this.activeMackUp = {
                prlNo: ''
            };
            // this.activeRow = { dummy: 0 };
        },
        // svg开始处理入口
        svgStartFn(inSourceUrl, value) {
            showLoading();
            if (inSourceUrl == null || typeof inSourceUrl == "undefined") {
                svg_opt.removeSvg();
                return;
            }
            let num = inSourceUrl.lastIndexOf(".") + 1;
            this.sourceExt = inSourceUrl.substring(num);
            this.sourceUrl = inSourceUrl;

            let EXT = this.sourceExt
            if (
                EXT == "png" ||
                EXT == "jpg" ||
                EXT == "gif" ||
                EXT == "bmp" ||
                EXT == "jpeg" ||
                EXT == "tif" ||
                EXT == "tiff"
            ) {
                this.isSourcePic = true;
                this.svgSourceUrl = require("@/assets/model/method-draw-image.svg");
            } else {
                this.isSourcePic = false;
                this.svgSourceUrl = inSourceUrl;
            }

            if (!this.svgSourceUrl || this.svgSourceUrl == "") {
                svg_opt.removeSvg();
                $('.right-CAD').html('NO Data');
                $('.right-CAD').css({
                    'display': 'flex',
                    'align-items': 'center',
                    'justify-content': 'space-evenly',
                    'font-size': '15px'
                });
                return;
            } else {
                // fetch(this.svgSourceUrl)
                //     .then(async response => {
                //         // 处理响应的数据
                //         if (response.status != 200) {
                //             svg_opt.removeSvg();
                //             $('.right-CAD').html('NO Data');
                //             $('.right-CAD').css({
                //                 'display': 'flex',
                //                 'align-items': 'center',
                //                 'justify-content': 'space-evenly',
                //                 'font-size': '15px'
                //             });
                //             return
                //         }
                //         window.open(this.currentItem.path);
                //     })
                //     .catch(async error => {
                //     });
            }



            this.isSvgLoading = true;
            svg_opt.setSvgLineWidthRatio(1.5);
            svg_opt.setSvgBoundingBoxRatio(0, 0, 1);
            svg_opt.setCanClickSelectMarkup(true);

            svg_opt.setCanEditSelectMarkup(false);
            svg_opt.setCanFitPositionAndScale(false);
            svg_opt.setEditDotWidthRatio(3);
            hideLoading();
            svg_opt.AddSvg(this.svgSourceUrl, "right-CAD", this.onSvgMousePosChange, true,
                    0,
                    0,
                    this.originExt == "wmf" ? 1 : -1);
            svg_opt.SetSvgMouseMode(0);
            svg_opt.setLoadCallBack(this.onSvgLoaded);
            svg_opt.setSelectCallBack(this.onLineGroupSelect);
            console.log(this.svgSourceUrl);

            setTimeout(() => {
                this.getFullFieldMarkApi(value);
            }, 1500);
        },
        // svg加载失败处理
        onSvgLoaded(error) {
            console.log("onSvgLoaded --- ", error);
            this.isSvgLoading = false;
            hideLoading();
            if (error) {
                console.log(error);
                return;
            }

            this.isSvgLoaded = true;

            if (this.isSourcePic) {
                svg_opt.changeSvgElementData({
                    tagName: "img-content",
                    paramName: "xlink:href",
                    newValue: this.sourceUrl
                });
            }
        },
        // 获取MarkUp数据
        async getFullFieldMarkApi(AreaCode) {
            showLoading()
            let dataJson = {
                AreaCode: AreaCode || this.MapValue
            };
            let res = await getFullFieldMark(dataJson);
            try {
                res.data.data.forEach(item => {
                    item.areaCode = Number(item.areaCode);
                    item.areaNo = Number(item.areaNo);
                    item.areaType = Number(item.areaType);
                    item.dtlNo = Number(item.dtlNo);
                    item.prlFntsiz = Number(item.prlFntsiz);
                    item.prlWidth = Number(item.prlWidth);
                    item.prlX = Number(item.prlX);
                    item.prlY = Number(item.prlY);
                    item.prlNo = Number(item.areaNo);
                    item.prlType = Number(item.areaType);

                })
            } catch (error) {

            }
            this.pfdData = [];
            if (res.data.code != 0) {
                return;
            }
            this.pfdData = res.data.data;
            // 模拟数据

            this.pfdData = this.genLineGroupAndShow(this.pfdData);

            // 绘制线组
            setTimeout(() => {
                svg_opt.clearAllMarkups();
                svg_opt.testAddLineGroupsByParams(this.pfdData);

                console.log(this.pfdData, "DDDDDDDDDDDdd")
                try {
                    svg_opt.changeSelectStatusById(this.activeMackUp.prlNo);
                } catch (error) {

                }
                hideLoading();

            }, 500);
        },
        /**
         * 处理线组数据
         */
        genLineGroupAndShow(originData) {
            let lineGroups = [];
            let lastPrl = "";

            console.log(originData);
            console.log(this.isSourcePic);

            // 遍历节点
            for (let i = 0; i < originData.length; i++) {
                let tempData = originData[i];
                let tempLineGroup = null;

                // 如果当前节点与上一个节点的线组号不同，新建线组，压入线组list
                if (lastPrl != tempData.prlNo) {
                    tempLineGroup = {};
                    lineGroups.push(tempLineGroup);

                    tempLineGroup.defaultLineColor = "#0000ff11";
                    tempLineGroup.defaultLineWidth = "10";
                    tempLineGroup.prlNo = tempData.prlNo;
                    tempLineGroup.groupItems = [];
                    tempLineGroup.sId = tempData.prlNo;
                    tempLineGroup.fEntType = "17";
                }

                // 取最近一个线组
                tempLineGroup = lineGroups[lineGroups.length - 1];

                // 如果线组为空 根据当前节点创建
                if (
                    tempLineGroup.groupItems.length == 0 ||
                    tempLineGroup.groupItems[
                        tempLineGroup.groupItems.length - 1
                    ].dtlNo != tempData.dtlNo
                ) {
                    let newItem = {};
                    newItem.dtlNo = tempData.dtlNo;
                    newItem.shapeType =
                        tempData.prlType == 1
                            ? "line"
                            : tempData.prlType == 2
                                ? "closeline"
                                : "rect";
                    newItem.fEntType = "17";
                    newItem.text = `${tempData.pltName} ${tempData.proName == 'No related' ? '' : ' :  ' + tempData.proName}`;
                    newItem.points = [];
                    if (this.isSourcePic) {
                        newItem.points.push({
                            x: tempData.prlX,
                            y: tempData.prlY < 0 ? Math.abs(tempData.prlY) : 0 - Math.abs(tempData.prlY),
                        });
                    } else {
                        newItem.points.push({
                            x: tempData.prlX,
                            y: tempData.prlY,
                        });
                    }
                    tempLineGroup.groupItems.push(newItem);
                } else if (
                    tempLineGroup.groupItems[
                        tempLineGroup.groupItems.length - 1
                    ].dtlNo == tempData.dtlNo &&
                    tempLineGroup.groupItems[
                        tempLineGroup.groupItems.length - 1
                    ].points.length >= 2
                ) {
                    let newItem = {};
                    newItem.dtlNo = tempData.dtlNo;
                    newItem.shapeType =
                        tempData.prlType == 1
                            ? "line"
                            : tempData.prlType == 2
                                ? "closeline"
                                : "rect";
                    newItem.fEntType = "17";
                    newItem.points = [];

                    newItem.points.push(
                        tempLineGroup.groupItems[
                            tempLineGroup.groupItems.length - 1
                        ].points[
                        tempLineGroup.groupItems[
                            tempLineGroup.groupItems.length - 1
                        ].points.length - 1
                        ]
                    );

                    if (this.isSourcePic) {
                        newItem.points.push({
                            x: tempData.prlX,
                            y: tempData.prlY < 0 ? Math.abs(tempData.prlY) : 0 - Math.abs(tempData.prlY),
                        });
                    } else {
                        newItem.points.push({
                            x: tempData.prlX,
                            y: tempData.prlY,
                        });
                    }
                    tempLineGroup.groupItems.push(newItem);
                } else if (
                    tempLineGroup.groupItems[
                        tempLineGroup.groupItems.length - 1
                    ].dtlNo == tempData.dtlNo
                ) {
                    if (this.isSourcePic) {
                        // newItem.points.push({ x: tempData.prlX, y: 0 - Math.abs(tempData.prlY) });
                        tempLineGroup.groupItems[
                            tempLineGroup.groupItems.length - 1
                        ].points.push({
                            x: tempData.prlX,
                            y: tempData.prlY < 0 ?  Math.abs(tempData.prlY) : 0 - Math.abs(tempData.prlY),
                        });
                    } else {
                        // newItem.points.push({ x: tempData.prlX, y: tempData.prlY });
                        tempLineGroup.groupItems[
                            tempLineGroup.groupItems.length - 1
                        ].points.push({ x: tempData.prlX, y: tempData.prlY });
                    }
                }

                lastPrl = tempLineGroup.prlNo;
            }

            // lineGroups[0].groupItems
            console.log(lineGroups)
            return lineGroups;
        },
        /**
     * 线组选中
     */
        onLineGroupSelect(e) {

            console.log('this.activeMackUp', this.activeMackUp);

            this.activeMackUp = e;
            this.activeRow = {};

            this.getPfdByPlantApi(e.prlNo);

        },

        // 切换编辑模式
        changeEditModeFn() {
            this.changeEditMode = this.changeEditMode == 0 ? 1 : 0;
        },

        // 开始关联
        async areaRelaPfdFn() {
            try {
                if (Object.keys(this.activeMackUp).length < 2 || Object.keys(this.activeRow).length < 2) {
                    this.$alert(this.$t('message.public.tip6'), '', {
                        confirmButtonText: 'OK',
                        type: 'warning',
                    });

                    return
                }
            } catch (error) {
                this.$alert(this.$t('message.public.tip6'), '', {
                    confirmButtonText: 'OK',
                    type: 'warning',
                });
                return
            }

            let dataJson = {};
            let res = await GetSavePlantRegTipsMsg(dataJson);
            if (res.data.code == 451) {
                this.$confirm(res.data.msg, '', {
                    confirmButtonText: 'OK',
                    cancelButtonText: 'Cancel',
                    type: 'warning'
                }).then(async () => {
                    let dataJson = {
                        "areaCode": this.MapValue,
                        "areaNo": this.activeMackUp.prlNo,
                        "pltCode": this.activeRow.pltCode,
                        "proCode": this.activeRow.proCode,
                    };
                    let res = await areaRelaPfd(dataJson);
                    if (res.data.code != 0) {
                        this.$alert(res.data.msg, '', {
                            confirmButtonText: 'OK',
                            type: 'warning',
                        });
                        return;
                    }
                    this.$message.success(res.data.msg);
                    this.getPfdByPlantApi(this.activeMackUp.prlNo);

                    this.getFullFieldMarkApi(this.MapValue);

                }).catch(() => {

                });
            }
        },
        // 接触关联

        async delAreaDataFn() {
            let dataJson = {};
            let res = await GetSavePlantRegTipsMsg(dataJson);
            if (res.data.code == 451) {
                this.$confirm(res.data.msg, '', {
                    confirmButtonText: 'OK',
                    cancelButtonText: 'Cancel',
                    type: 'warning'
                }).then(async () => {
                    let dataJson = {
                        "areaCode": this.MapValue,
                        "areaNo": this.activeMackUp.prlNo,
                    };
                    let res = await delAreaData(dataJson);
                    if (res.data.code != 0) {
                        this.$alert(res.data.msg, '', {
                            confirmButtonText: 'OK',
                            type: 'warning',
                        });
                        return;
                    }
                    this.$message.success(res.data.msg);
                    this.getPfdByPlantApi();
                    this.getFullFieldMarkApi(this.MapValue);
                }).catch(() => {

                });
            }
        },

        // 开始
        initFn() {

            this.getPlantApi(1, 1000);

            this.getFullFieldMapListApi();
        }

    },
    created() { },
    mounted() {
        this.tableHeight = $(".Tbale").height();

        this.initFn();
    },
    beforeDestroy() {

    },
    destroyed() { },
};
</script>
<style lang="scss" scoped>
.Table {
    display: flex;
    height: 100%;
    border-top: 1px solid #e1e1e1;
    padding-top: 12px;

    .left_Nav {
        min-width: 238px;
        height: 100%;
        margin-right: 16px;

        .row {
            width: 100%;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 12px;

            .form-row-label {
                color: rgba(0, 0, 0, 0.85);
                min-width: 45px;
            }

            .form-ipt {
                width: 100%;
                height: 24px;

                ::v-deep .el-input__inner {
                    height: 24px;
                    background: #fff;
                }

                ::v-deep .el-input__icon {
                    line-height: 24px;
                }
            }
        }

        .Tbale {
            height: calc(100% - 125px);
        }

        .bh-footer {
            width: 100%;
            height: 38px;
            background: #e9e9e9;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .bottonBtn {
            margin-top: 10px;
        }
    }

    .right_Content {
        background-color: #FFF;
        width: 100%;
        height: 100%;

        .row {
            display: flex;
            justify-content: flex-start;
            background-color: rgb(248, 248, 248);
            height: 37px;

            .selectViewLabel {
                margin-right: 20px;
                font-size: 14px;
                color: rgba(0, 0, 0, 0.65);
            }

            .form-ipt {
                width: 200px;
                height: 24px;

                ::v-deep .el-input__inner {
                    height: 24px;
                    background: #fff;
                }

                ::v-deep .el-input__icon {
                    line-height: 24px;
                }
            }

            span {
                width: 38px;
                height: 24px;
                margin: 0 20px;
                color: #565656;
                background: #f8f8f8;
                border-radius: 4px;
                text-align: center;
                line-height: 24px;
                border: 1px solid rgba(0, 0, 0, 0.15);
                padding: 0 4px;
            }

            .iconfont {
                width: 24px;
                height: 24px;
                font-size: 20px;
                margin: 0;
                border: none;
                cursor: pointer;
                margin-right: 20px;
            }

            .refresh {
                min-width: 40px;
                height: 24px;
                border-radius: 4px;
                border: 1px solid #d9d9d9;
                display: flex;
                align-items: center;
                justify-content: center;
                cursor: pointer;
                text-align: center;

                .iconfont {
                    margin: 0 4px;
                    font-size: 17px;
                    height: 24px;
                    line-height: 24px;
                }
            }

            .isActive {
                color: #df1222;
            }
        }


        .right-CAD {
            width: 100%;
            height: 90%;
            cursor: pointer;
            position: relative;

        }


    }
}

.mask::after {
    content: '';
    display: block;
    width: 100%;
    height: 100%;
    cursor: not-allowed;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 50;
}
</style>